package Services

import (
	"Ahq/Models"
	"bytes"
	"fmt"
	"time"

	"github.com/Vale-sail/maroto/pkg/consts"
	"github.com/Vale-sail/maroto/pkg/pdf"
	"github.com/Vale-sail/maroto/pkg/props"
)

type pdfConfig struct {
	Fsize      float64
	FRowHeight float64
}

func createPdf() pdf.Maroto {
	m := pdf.NewMaroto(consts.Portrait, consts.A4)
	m.SetPageMargins(5, 20, 0)
	m.AddUTF8Font("NotoSansSC", "", "KaiTi-1.ttf")
	m.AddUTF8Font("jizi", "", "jizi.ttf")
	m.AddUTF8Font("NotoSansSC", "I", "KaiTi-1.ttf")
	m.AddUTF8Font("NotoSansSC", "B", "KaiTi-1.ttf")
	m.AddUTF8Font("NotoSansSC", "BI", "KaiTi-1.ttf")
	return m
}

func Pdf(paper Models.Paper) (bytes.Buffer, error) {
	pdfConfig := pdfConfig{14, 8}
	bT := time.Now()
	defer func() {
		eT := time.Since(bT)
		fmt.Println("pdf Run time: ", eT)
	}()

	m := createPdf()

	m.RegisterHeader(func() {
		m.Row(10, func() {
			m.ColSpace(1)
			// m.Col(1, func() {
			// 	m.QrCode("https://gitee.com/weiyi/AHundredQuestions")
			// })
			m.Col(11, func() {
				m.Text(paper.Title, props.Text{
					Size:   24,
					Family: "jizi",
					// Extrapolate: true,
					Align: consts.Left,
				})

			})
		})
		m.Row(10, func() {
			m.ColSpace(1)
			m.Col(11, func() {
				m.Text(paper.SubTitle, props.Text{
					Size:   12,
					Family: "NotoSansSC",
					Align:  consts.Left,
					Top:    2,
				})
			})
		})
		m.Row(5, func() { m.ColSpace(12) })
	})
	m.RegisterFooter(func() {
		m.Row(15, func() {
			m.ColSpace(12)
		})

		m.Row(30, func() {
			m.Col(12, func() {
				m.FileImage("QCODE.png", props.Rect{Center: true})
			})
		})
	})

	// m.Line(1)
	fSize := len(paper.Formulas)
	for i := 0; i < 20; i++ {
		m.Row(pdfConfig.FRowHeight, func() {
			m.ColSpace(1)
			for j := 0; j < 5; j++ {
				index := i*5 + j
				if index < fSize {
					m.Col(2, func() {
						m.Text(paper.Formulas[index].WithEqualSign(), props.Text{
							Size:  pdfConfig.Fsize,
							Align: consts.Left,
						})
					})
				} else {
					m.ColSpace(2)
				}

			}

		})
	}

	return m.Output()

}
